<template>
    
    <!-- 组件的模板 -->
    <div class="page form-report">
        <div class="weui-cells weui-cells_form">
            <div class="weui-cell">
                <div class="weui-cell__hd"><label class="weui-label">表单名称</label></div>
                <div class="weui-cell__bd">
                    <input class="weui-input input_blur" type="text" placeholder="请输入" maxlength="20" v-model="formInfo.title" @blur="saveToCache">
                </div>
            </div>
        </div>
        <div class="weui-cells__title">表单描述</div>
        <div class="weui-cells weui-cells_form">
            <div class="weui-cell">
                <div class="weui-cell__bd">
                    <textarea class="weui-textarea input_blur" placeholder="请说明表单填写要求" rows="3" maxlength="50" v-model="formInfo.desc" @blur="saveToCache"></textarea>
                    <div class="weui-textarea-counter desc_cont"><span>{{formInfo.desc.length}}</span>/50</div>
                </div>
            </div>
        </div>
        <div class="weui-cells__title">表单须填写字段</div>
        <div class="weui-cells">
            <div id="items">
                <div class="relative" v-for="item in formInfo.format_info">
                    <div class="delete" @click="delForm($index)">删除</div>
                    <div class="weui-cell swiped-cell" @click="gotoDesign($index,item)">
                        <div class="weui-cell__bd">
                            <p><span class="title color_333">{{item.info.title}}</span></p>
                        </div>
                        <span class="btn-drag active glyphicon-move" v-if="formInfo.format_info.length > 1"><span></span><span></span><span></span></span>
                        <!-- <span class="btn-drag glyphicon-move"><span></span><span></span><span></span></span> -->
                    </div>
                </div>
            </div>
        </div>
        <a class="add-item touch" href="javascript:;" @click="addform">
            <span class="icon bg_sprite"></span>
            <span>添加填写项</span>
        </a>
        <div class="placehold_div"></div>
        <a href="javascript:;" v-if="formInfo.format_info.length > 0 && formInfo.title && sortEnd" @click="gotoFormPreview" class="weui-btn weui-btn_default fixed com-border-top" :style="isIphoneX?'padding-bottom: 20px;height:auto;':''">预览</a>
    </div>




    <!-- <div class="weui-cells__title">表单基本信息</div>class="glyphicon-move" -->
    <!-- <div class="weui-cells weui-cells_form">
        <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">表单名称</label></div>
            <div class="weui-cell__bd">
                <input class="weui-input" type="text" placeholder="请输入表单名称" maxlength="20" v-model="formInfo.title" @blur="saveToCache"/>
            </div>
        </div>
    </div>
    <div class="weui-cells weui-cells_form">
        <div class="weui-cell">
            <div class="weui-cell__bd">
                <p>表单描述</p>
            </div>
        </div>
        <div class="weui-cell">
            <div class="weui-cell__bd">
                <textarea class="weui-textarea" placeholder="请输入表单描述" rows="3" maxlength="50" v-model="formInfo.desc" @blur="saveToCache"></textarea>
                <div class="weui-textarea-counter"><span>{{formInfo.desc.length}}</span>/50</div>
            </div>
        </div>
    </div>
    <div class="weui-cells bgc">
        <div class="weui-cell">
            <div class="weui-cell__bd">
                <p>表单须填写字段</p>
            </div>
        </div>
    </div>

    <div id="">
        <div class="relative" v-for="item in formInfo.format_info">
            <div class="weui-cells swiped-cell" @click="gotoDesign($index,item)">
                <div class="weui-cell">
                    <div class="weui-cell__bd">
                        <p>{{item.info.title}}</p>
                    </div>
                    <div class="weui-cell__ft"><img class="glyphicon-move" src="../../static/imgs/listicon.png" alt=""></div>
                </div>
            </div>
            <div class="delete" @click="delForm($index)">删除</div>
        </div>
    </div>

    <div class="weui-cells">
        <div class="weui-cell addnewform" @click="addform">
            <div class="weui-cell__bd">
                <p><span>+</span>添加填写项</p>
            </div>
        </div>
    </div> -->
</template>

<script>
let ajaxEnd = true
    /**
     *  引入工具类库 或 Native API
     *  example : import widget from 'gapi/widget'
     */

    import Sortable from 'sortablejs'
    import Sw from 'swiped'
    import widget from 'gapi/widget.js'
    import cache from 'gapi/cache.js'
    import clientUi from 'gapi/clientUi.js'
    import * as util from 'js/util.js'
    import commonPage from 'clientApi/commonPage.js'
    // commonPage.canPullWebView(true)
    import KCApiApp from 'clientApi/KCApiApp.js'


    /**
     *  引入组件 以及 组件接口(Action)
     *  example : import Somecomponents from 'components/Somecomponents/Somecomponents'
     */
    /**
     *  组件实例对象
     */
    export default {
        components: {

        },
        data: function(){
            return{
                team_id: 0,
                project_id: 0,
                formInfo: {
                    title: '',
                    desc: '',
                    format_info: [
                        // {
                        //     "id": "1",
                        //     "type": "SingleText",
                        //     "name": "单行文字",
                        //     "info": {
                        //                 "title": "草莓味销量",
                        //                 value: '',
                        //                 "tip": "请直接输入销量,没有输入0",
                        //                 "required": 1 //0-否 1-是
                        //             }
                        // },
                        // {
                        //     "id": "2",
                        //     "type": "TextArea",
                        //     "name": "多行文字",
                        //     "info": {
                        //                 "title": "今日竞品种类",
                        //                 value: '',
                        //                 "tip": "请直接输入竞品的产品名称",
                        //                 "required": 0 //0-否 1-是
                        //             }
                        // }
                        // {
                        //     "id": "3",
                        //     "type": "Number",
                        //     "name": "数字",
                        //     "info": {
                        //                 "title": "奶油味销量",
                        //                 value: '',
                        //                 "tip": "请直接输入销量,没有输入0",
                        //                 "required": 0 //0-否 1-是
                        //             }
                        // },
                        // {
                        //     "id": "4",
                        //     "type": "Select",
                        //     "name": "下拉选项",
                        //     "info": {
                        //                 "title": "请选择门店",
                        //                 value: '',
                        //                 "tip": "请直接选择所在门店",
                        //                 "options": ["美廉美", "家乐福", "沃尔玛"],
                        //                 "required": 0 //0-否 1-是
                        //             }
                        // },
                        // {
                        //     "id": "5",
                        //     "type": "Date",
                        //     "name": "日期",
                        //     "info": {
                        //                 "title": "请选择日期",
                        //                 value: '',
                        //                 "tip": "请直接输入竞品的产品名称",
                        //                 "required": 0 //0-否 1-是
                        //             }
                        // },
                        // {
                        //     "id": 6,
                        //     "type": "Location",
                        //     "name": "位置",
                        //     "info": {
                        //         "title": "",
                        //         "value": {
                        //             "lat": "",
                        //             "lng": "",
                        //             "addr": ""
                        //         },
                        //         "tip": "",
                        //         "required": 1
                        //     }
                        // },
                        // {
                        //     "id": 7,
                        //     "type": "Imageview",
                        //     "name": "照片",
                        //     "info": {
                        //         "title": "",
                        //         "value": [],
                        //         "tip": "",
                        //         "required": 1,
                        //         "isSelectImg": 0
                        //     }
                        // }

                    ]
                },
                form_id: 0,  //如果是编辑已有表单则会有此项
                delete_format:[],
                temp_info: {},
                sortEnd: true
            }
        },
        computed: {
            isIphoneX: function(){
                return util.isIphoneX()
            }
        },
        vuex: {
            getters: {
                

            },
            actions: {

            }
        },
        methods: {
            /**
             * 初始化
             * @method init
             * @public
             * @return {Null} void
             */
            init (){
                this.form_id = util.getUrddataString('form_id');
                let originalStatus = util.getUrddataString('originalStatus');
                // alert(originalStatus)
                // alert(this.form_id)
                //获取表单内容
                cache.getCache('user_info', (data) => {
                    this.team_id = data.team_id
                    this.project_id = data.project_id
                    if(this.form_id){
                        util.ajax({
                            url: '/form/info',
                            type: 'GET',
                            data: {
                                team_id: data.team_id,
                                project_id: data.project_id,
                                form_id: this.form_id
                            },
                            timeout: 10000,
                            success: (data) => {
                                // success
                                // alert(JSON.stringify(data))
                                if(data.errno == 0){
                                    this.formInfo.title = data.data.title
                                    this.formInfo.desc = data.data.desc
                                    this.formInfo.format_info = data.data.format_info
                                    // alert(JSON.stringify(data))
                                    cache.setCache('formInfo', this.formInfo, 10000)
                                    setTimeout(this.swiped,100)
                                }else{
                                    // widget.toast('服务器异常')
                                    widget.toast(data.errmsg)
                                }
                                
                            },
                            error: (xhr, status) => {
                                // error
                                widget.toast('服务器异常')
                            },
                            noNetwork: () => {
                                // 无网络的回调
                                widget.toast('网络连接失败，请检查网络')
                            }
                        })
                    }
                })
                // $.ajax({
                //     type: 'GET',
                //     url: `${util.devDomain}/sea/api/1.0/client/v1/form/format`,
                //     success: (res) => {
                //         alert(res.errmsg)
                //     }
                // })
                //如果不是从模板选择页跳转进来的  prevPageName === null
                // let prevPageName = util.getUrddataString('prevPageName')
                // alert(prevPageName)
                cache.getCache('formInfo', (data) => {
                    if(data){
                        // if(prevPageName === 'selectFormTemp'){
                        clientUi.showDialog('提醒', '当前有上次编辑未保存的表单,是否恢复?', (status) => {
                            if(status.status === '1'){
                                this.formInfo = data
                                setTimeout(this.swiped,100)
                                // cache.deleteCache('formInfo')
                            }else{
                                cache.deleteCache('formInfo')
                            }
                        })
                        // }else{
                        //     this.formInfo = data
                        //     widget.toast('读取缓存中')
                        // }
                    }else{
                        // widget.toast('没有缓存')
                        this.temp_info = JSON.parse(util.getUrddataString('temp_info'));
                            // alert(this.temp_info)
                        if(this.temp_info){
                            this.formInfo.title = this.temp_info.title
                            this.formInfo.desc = this.temp_info.desc
                            this.formInfo.format_info = this.temp_info.format_info
                            cache.setCache('formInfo', this.formInfo, 10000)
                            setTimeout(this.swiped,100)
                        }
                    }
                })
                

                commonPage.updateTitleBar({
                    backAction: 'checkChange',    // 点击返回按钮的动作（即回调函数名称）
                    // leftDisplay: false,            // 是否显示左按钮
                    // leftText: '',                // 左按钮文案
                    leftAction: 'checkChange',    // 点击左按钮的动作（即回调函数名称）
                    rightDisplay: true,            // 是否显示右按钮
                    rightText: '完成',            // 右按钮文案
                    rightAction: 'saveResume'    // 点击右按钮的文案（即回调函数名称）
                })
                //点击右上角完成按钮
                window.saveResume = () => {
                    // alert(JSON.stringify(this.formInfo))
                    if(this.formInfo.title && this.formInfo.format_info.length > 0){

                        this.formInfo.format_info.forEach((obj, index) => {
                            if(obj.sign){
                                delete obj.sign
                            }
                            return obj.order = index + 1
                        })
                        // return
                        //表单上传到服务器
                        commonPage.loadPageStatus('loading')
                        if(this.form_id){
                            // alert(JSON.stringify(this.formInfo.format_info))
                            //编辑表单
                            util.ajax({
                                url: '/form/edit',
                                type: 'POST',
                                data: {
                                    form_id: this.form_id,
                                    team_id: this.team_id,
                                    project_id: this.project_id,
                                    title: this.formInfo.title,
                                    desc: this.formInfo.desc,
                                    format_info: this.formInfo.format_info,
                                    delete_format: this.delete_format
                                },
                                timeout: 10000,
                                success: (data) => {
                                    commonPage.loadPageStatus('loadSuccess')
                                    // success
                                    // alert(JSON.stringify(data))
                                    if(data.errno == 0){
                                        // alert(JSON.stringify(this.formInfo.format_info))
                                        widget.toast('表单修改成功')
                                        //删除缓存
                                        cache.deleteCache('formInfo')
                                        //跳至表单设置
                                        // let encodeStr = encodeURIComponent(`form_id=${this.form_id}`)
                                        // location.href = `dmsaas://SetupFormInfo?urdData=${encodeStr}`
                                        //跳到表单设置列表页
                                        commonPage.goBack(1)
                                    }else{
                                        // widget.toast('服务器异常')
                                        widget.toast(data.errmsg)
                                        // alert(data.errmsg)
                                    }
                                },
                                error: (xhr, status) => {
                                    commonPage.loadPageStatus('loadSuccess')
                                    // error
                                    widget.toast('服务器异常')
                                },
                                noNetwork: () => {
                                    commonPage.loadPageStatus('loadSuccess')
                                    // 无网络的回调
                                    widget.toast('网络连接失败，请检查网络')
                                }
                            })
                        }else{
                            //新建表单
                            // alert(this.project_id)
                            if(!ajaxEnd)return
                            ajaxEnd = false
                            util.ajax({
                                url: '/form',
                                type: 'POST',
                                data: {
                                    team_id: this.team_id,
                                    project_id: this.project_id,
                                    title: this.formInfo.title,
                                    desc: this.formInfo.desc,
                                    format_info: this.formInfo.format_info
                                },
                                timeout: 10000,
                                success: (data) => {
                                    commonPage.loadPageStatus('loadSuccess')
                                    // success
                                    if(data.errno == 0){
                                        this.form_id = data.data.form_id
                                        // alert(JSON.stringify(data))
                                        widget.toast('表单创建成功')
                                        //删除缓存
                                        cache.deleteCache('formInfo')
                                        //跳至表单设置
                                        let encodeStr = encodeURIComponent(`form_id=${this.form_id}&type=1`)
                                        location.href = `dmsaas://SetupFormInfo?urdData=${encodeStr}`
                                    }else{
                                        ajaxEnd = true
                                        // widget.toast('服务器异常')
                                        widget.toast(data.errmsg)
                                        // alert(data.errmsg)
                                    }
                                },
                                error: (xhr, status) => {
                                    commonPage.loadPageStatus('loadSuccess')
                                    // error
                                    ajaxEnd = true
                                    widget.toast('服务器异常')
                                },
                                noNetwork: () => {
                                    commonPage.loadPageStatus('loadSuccess')
                                    ajaxEnd = true
                                    // 无网络的回调
                                    widget.toast('网络连接失败，请检查网络')
                                }
                            })
                        }

                    }else{
                        if(!this.formInfo.title){
                            widget.toast(`请填写表单名称`)
                        }else if(this.formInfo.format_info.length <= 0){
                            widget.toast(`请至少添加一条填写项`)
                        }
                    }
                }
                //点击返回按钮
                window.checkChange = () => {
                    
                        // if(this.formInfo.title || this.formInfo.desc || this.formInfo.format_info.length){

                        //     clientUi.showDialog('提醒', '当前有未保存的表单,是否放弃提交?', (status) => {
                        //         if(status.status === '1'){
                                    //删除缓存
                                    cache.deleteCache('formInfo')
                                    //根据原来的状态决定是否更改表单状态
                                    if(this.form_id && originalStatus == 1){
                                        // alert(1231232131)
                                        util.ajax({
                                            url: '/form/status',
                                            type: 'POST',
                                            data: {
                                                team_id: this.team_id,
                                                project_id: this.project_id,
                                                form_id: this.form_id,
                                                status: 1
                                            },
                                            timeout: 10000,
                                            success: (data) => {
                                                // success
                                                if(data.errno == 0){
                                                    commonPage.goBack(1)
                                                }else{
                                                    // widget.toast('服务器异常')
                                                    widget.toast(data.errmsg)
                                                    // alert(JSON.stringify(data))
                                                }
                                            },
                                            error: (xhr, status) => {
                                                // error
                                                widget.toast('服务器异常')
                                            },
                                            noNetwork: () => {
                                                // 无网络的回调
                                                widget.toast('网络连接失败，请检查网络')
                                            }
                                        })
                                    }else{
                                        if(util.getUrddataString('page_type') === 'formTempPreview'){
                                            // if(util.OS()=='ios'){
                                            //     cache.getCache('webViewID', (data) => {
                                            //         commonPage.goBack(1, '', data)
                                            //     })
                                            // }else{
                                                window.location.href = `dmsaas://SelectFormTemp`
                                            // }
                                        }else{
                                            commonPage.goBack()
                                        }
                                        
                                    }
                                    
                            //     }
                            // })

                        // }else{
                        //     cache.deleteCache('formInfo')
                        //     commonPage.goBack()
                        // }
                        
                }
                window.loadData = () => {
                    // location.reload()
                    // alert(JSON.stringify(tempObj))
                    // commonPage.dataDownloadFinished()
                    cache.getCache('formInfo', (data) => {
                        if(data){
                            this.formInfo.format_info = data.format_info
                            // alert(JSON.stringify(data))
                            setTimeout(this.swiped,100)
                            
                        }
                        // else{
                        //     let tempObj = {
                        //         title: '',
                        //         desc: '',
                        //         format_info: []
                        //     }
                        //     this.formInfo = tempObj
                        //     widget.toast('没有缓存')
                        // }
                    })
                }
            },
            addform (){
                // $('.input_blur')[0].blur()
                // location.href = `dmsaas://ContentDesign`
                setTimeout(() => {
                    KCApiApp.showDesignWindow()
                }, 200)
                
            },
            delForm (index){
                // console.log(index);
                if(this.formInfo.format_info[index].id !== ''){
                    this.delete_format.push(this.formInfo.format_info[index].id)
                }
                // alert(JSON.stringify(this.delete_format))
                this.formInfo.format_info.splice(index,1)
                //删除以后也要重新缓存新数据
                cache.setCache('formInfo', this.formInfo, 10000)
            },
            saveToCache (){
                // if(this.formInfo.title || this.formInfo.desc || this.formInfo.format_info.length){
                //     cache.setCache('formInfo', this.formInfo, 10000)
                // }else{
                //     widget.toast('formInfo没有内容')
                // }
                
            },
            //点击字段跳到相应字段设置页
            gotoDesign (matindex,item){
                // alert(item)
                // alert(info.tip)
                let urd = 'DesignFormSingle'
                switch(item.type){
                    case 'SingleText':
                        urd = 'DesignFormSingle';
                        break;
                    case 'TextArea':
                        urd = 'DesignFormArea';
                        break;
                    case 'Number':
                        urd = 'DesignFormNumb';
                        break;
                    case 'Select':
                        urd = 'DesignFormSelect';
                        break;
                    case 'Date':
                        urd = 'DesignFormDate';
                        break;
                    case 'Location':
                        urd = 'DesignFormLoca';
                        break;
                    case 'Imageview':
                        urd = 'DesignFormImg';
                        break;
                    default :
                        urd = 'DesignFormSingle';
                        break;
                }
                let designInfo = JSON.stringify(item)
                let encodeStr = encodeURIComponent(`designInfo=${designInfo}&matindex=${matindex}`)
                location.href = `dmsaas://${urd}?urdData=${encodeStr}`
            },
            swiped (){
                let s = Swiped.init({
                    query: '#items .swiped-cell',
                    list: true,
                    right: 70
                });
            },
            gotoFormPreview (){
                let temp_info = JSON.stringify(this.formInfo)
                let encodeStr = encodeURIComponent(`temp_info=${temp_info}`)
                location.href = `dmsaas://FormTempPreview?urdData=${encodeStr}`
            }
        },
        created(){

            this.init();
            
        },
        ready(){
            // this.swipedAndSort()
            const that = this;
            Sortable.create(items, {
                handle: '.glyphicon-move',
                animation: 100,
                onStart: function(evt){
                    that.sortEnd = false
                },
                onEnd: function (evt){
                    that.sortEnd = true
                    // alert(evt.oldIndex)
                    let tempObj = that.formInfo.format_info[evt.oldIndex]
                    that.formInfo.format_info.splice(evt.oldIndex, 1)
                    that.formInfo.format_info.splice(evt.newIndex, 0, tempObj)
                    // alert(JSON.stringify(that.formInfo.format_info))
                    //删除以后也要重新缓存新数据
                    cache.setCache('formInfo', that.formInfo, 10000)
                }
            });
        }
        
    }

    
</script>

<!-- CSS 样式 -->
<style src="../../node_modules/weui/dist/style/weui.css"></style>
<style src="../../static/css/common2.css"></style>
<style src="../../static/css/form-report.css"></style>
<style type="text/css">
    /*html body{
        height: inherit;
    }*/
    .relative{
        position: relative;
        background-color: #FF3B30;
    }
    .swiped-cell{
        background-color: #fff;
        z-index: 0;
    }
    .delete{
        position: absolute;
        z-index: 0;
        /*background-color: red;*/
        right:0;
        top:0;
        width:70px;
        text-align: center;
        line-height: 48px;
        color:#fff;
    }
    .sortable-chosen{
        -webkit-box-shadow: 0 0 15px #888888;
        -moz-box-shadow: 0 0 15px #888888;
        -ms-box-shadow: 0 0 15px #888888;
        -o-box-shadow: 0 0 15px #888888;
        box-shadow: 0 0 15px #888888;
    }
    div.placehold_div{
        /*height:46px;*/
        height:78px;
        width:100%;
    }
    div.desc_cont{
        font-size: 12px;
        color: #999;
    }
    div.weui-cell__bd span.color_333{
        color:#333;
    }
</style>

